package pro.cherish.knowledgeweb.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import pro.cherish.knowledgeruntime.web.interceptor.WebInterceptor;
import pro.cherish.knowledgeweb.filter.XssFilter;

import javax.servlet.DispatcherType;
import java.util.List;

/**
 * @author 创建人：cherish
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2019-11-03 cherish 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：WebConfig
 * @Description 功能说明：
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2019-11-03 cherish
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    List<WebInterceptor> interceptorList;

    /**
     * xss 过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean<XssFilter> xssFilterRegistration() {
        FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<XssFilter>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns("/*");
        registration.setName("xssFilter");
        registration.setOrder(Integer.MAX_VALUE);
        return registration;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册监听器 同时设置其拦截路径
        if (interceptorList != null) {
            for (WebInterceptor interceptor : interceptorList) {
                registry.addInterceptor(interceptor).addPathPatterns(interceptor.patternUrl()).order(interceptor.order());
            }
        }
    }
}
